package org.bees.cms.web.tag;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspWriter;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.bees.cms.common.Order;
import org.bees.cms.core.Domain;
import org.bees.cms.web.util.velocity.Context;
import org.bees.cms.web.util.velocity.element.Column;

public class Table extends Tag {
	private static final long serialVersionUID = -1318456609143175567L;

	private String columns;// json格式的
	private Order order;
	private String by;
	private List<? extends Domain> domains; // 通过表达式得到action存放在 范围对象里的 领域类List集合
	private List<Column> attributes = new ArrayList<Column>(); // 解析后的列元素集合

	@Override
	protected void before() throws Exception {
		JSONArray array = JSONArray.fromObject(columns == null || columns.trim().equals("") ? "[]" : columns);
		for (int i = 0; i < array.size(); i++) {
			JSONObject json = array.getJSONObject(i);
			Column column = new Column();
			column.from(json);
			attributes.add(column);
		}
	}

	@Override
	protected void analyze(JspWriter writer) throws Exception {
		Template template = Velocity.getTemplate("table.vm.html");
		Context context = context();
		context.put("columns", attributes);
		context.put("order", order);
		context.put("by", by);
		context.put("domains", domains);
		template.merge(context, writer);
	}

	@Override
	protected void after() throws Exception {
		columns = null;
		domains = null;
		attributes.clear();
	}

	public String getAttributes() {
		return columns;
	}

	public void setAttributes(String columns) {
		this.columns = columns;
	}

	public String getColumns() {
		return columns;
	}

	public void setColumns(String columns) {
		this.columns = columns;
	}

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public String getBy() {
		return by;
	}

	public void setBy(String by) {
		this.by = by;
	}

	public List<? extends Domain> getDomains() {
		return domains;
	}

	public void setDomains(List<? extends Domain> domains) {
		this.domains = domains;
	}

	public void setAttributes(List<Column> attributes) {
		this.attributes = attributes;
	}

}
